# -*- coding:utf-8 -*-

## =====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
import time
from tkMessageBox import *

from Persistance import *
from iCalendar import CalendarGUI
from iNotes import NotesGUI
from iPerson import PersonListGUI
from iDiscount import DiscountListGUI
from iProduct import ProductListGUI
from iParking import ParkingListGUI
from iService import ServiceListGUI
from iSchedule import Event
from iTime import TimePopupGUI
from iStayPDF import StayPDF

class StayGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Réservation")
		self.balloon=balloon
		self.imgLinks=PhotoImage(file="img/links_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.imgNotes=PhotoImage(file="img/edit.gif")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgCalendar=PhotoImage(file="img/calendar.gif")
		self.imgTime=PhotoImage(file="img/time_icon.gif")
		self.imgPrint=PhotoImage(file="img/print_icon.gif")
		self.hoursListCB = Glob.HOURS_LIST
		self.minutesListCB = Glob.MINUTES_LIST
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Reservation-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Reservation-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tStayGUI\tStart")
		self.makeStay()

	 # DEBUT de la gestion du module Stay ------------------------------------------------------------------------------------------------------------------
	def clearFieldStay(self):
		# Mise a zéro des champs
		n = self.getStayVoucher()
		self.stayValues[0].set(n)
		self.stayValues[1].set("")
		self.stayValues[2].set("")
		self.stayValues[3].set("")
		self.stayValues[4].set("")
		self.stayValues[5].set("")
		self.stayValues[6].set("")
		self.stayValues[7].set("O")
		self.stayValues[8].set("")
		self.stayValues[9].set("")
		self.stayValues[10].set("")
		self.stayValues[11].set("")
		self.stayValues[12].set("")
		self.stayValues[13].set("")
		# Remise à zéro des ComboBox
		self.stayStatusCB.selectitem(0)
		self.hourInStayCB.selectitem(0)
		self.minInStayCB.selectitem(0)
		self.hourOutStayCB.selectitem(0)
		self.minOutStayCB.selectitem(0)
		self.stayHourIn=StringVar()
		self.stayMinuteIn=StringVar()
		self.stayHourOut=StringVar()
		self.stayMinuteOut=StringVar()
		self.listObject=[Person, Discount, Stay]
		self.stayProductChoiceBt.config(state=DISABLED)
		self.stayServiceChoiceBt.config(state=DISABLED)
		self.stayParkinkChoiceBt.config(state=DISABLED)
		self.stayResidentBt.config(state=DISABLED)
		self.stayStayOrderBt.config(state=DISABLED)

	def getStayVoucher(self):
		result = StayVoucher.select()
		n = time.strftime("%Y%m" ,time.localtime())+str(1000+result.count())
		StayVoucher(number=n, createDate=datetime.datetime.now())
		return n

	def set(self, e):
		result = Stay.select(Stay.q.id==int(e.stayID))
		for row in result:
			self.selectedStay = row
		self.listObject[0]=self.selectedStay.contact
		self.listObject[1]=self.selectedStay.discount
		self.listObject[2]=self.selectedStay
		self.stayValues[1].set(self.listObject[0].fname+" - "+self.listObject[0].lname)
		if self.listObject[1] != None:self.stayValues[6].set(self.listObject[1].code)
		if self.selectedStay.voucher != None:self.stayValues[0].set(self.selectedStay.voucher)
		if self.selectedStay.notes != None:self.stayValues[8].set(self.selectedStay.notes)
		if self.selectedStay.checkIn != None:
			# Affichage de la date de Début (self.selectedStay .dateIn)
			self.stayValues[2].set(self.selectedStay.checkIn.strftime("%d/%m/%Y"))
			# Affichage de l'heure de Début dans la ComboBox 
			count = 0
			for h in self.hoursListCB:
				if h == self.selectedStay.checkIn.strftime("%H"): self.hourInStayCB.selectitem(count)
				count+=1
			# Affichage des minutes de Début dans la ComboBox
			count = 0
			for m in self.minutesListCB:
				if m == self.selectedStay.checkIn.strftime("%M"): self.minInStayCB.selectitem(count)
				count+=1
			# Mise à jour des variables heure et minutes de Début
			self.stayHourIn.set(self.selectedStay.checkIn.strftime("%H"))
			self.stayMinuteIn.set(self.selectedStay.checkIn.strftime("%M"))
		if self.selectedStay.checkOut != None:
			# Affichage de la date de Fin (self.selectedStay .dateOut)
			self.stayValues[4].set(self.selectedStay.checkOut.strftime("%d/%m/%Y"))
			# Affichage de l'heure de Fin dans la ComboBox 
			count = 0
			for h in self.hoursListCB:
				if h == self.selectedStay.checkOut.strftime("%H"): self.hourOutStayCB.selectitem(count)
				count+=1
			# Affichage des minutes de Fin dans la ComboBox
			count = 0
			for m in self.minutesListCB:
				if m == self.selectedStay.checkOut.strftime("%M"): self.minOutStayCB.selectitem(count)
				count+=1
			# Mise à jour des variables heure et minutes de Fin
			self.stayHourOut.set(self.selectedStay.checkOut.strftime("%H"))
			self.stayMinuteOut.set(self.selectedStay.checkOut.strftime("%M"))
		# Affichage du Type dans la ComboBox
		status = ((u"O", 0),(u"R", 1),(u"F", 2),(u"A", 3),)
		for n in status:
			if n[0] == self.selectedStay.status: self.stayStatusCB.selectitem(n[1])
		# Affichage de la présence de produits lié a ce séjour
		self.resultProduct = ProductChoice.select(ProductChoice.q.stay==self.selectedStay)
		count=0
		for row in self.resultProduct:
			count+=1
		if count < 2:
			self.stayValues[9].set(str(count)+" Produit")
		else:
			self.stayValues[9].set(str(count)+" Produits")
		# activation du bouton ProductChoice rattaché
		self.stayProductChoiceBt.config(state=NORMAL)
		# Affichage de la présence de Service lié a ce séjour
		self.resultService = ServiceChoice.select(ServiceChoice.q.stay==self.selectedStay)
		count=0
		for row in self.resultService:
			count+=1
		if count < 2:
			self.stayValues[10].set(str(count)+" Service")
		else:
			self.stayValues[10].set(str(count)+" Services")
		# activation du bouton ServiceChoice rattaché
		self.stayServiceChoiceBt.config(state=NORMAL)
		# Affichage de la présence de ParkingChoice lié a ce séjour
		self.resultParking = ParkingChoice.select(ParkingChoice.q.stay==self.selectedStay)
		count=0
		for row in self.resultParking:
			count+=1
		if count < 2:
			self.stayValues[11].set(str(count)+" Parking")
		else:
			self.stayValues[11].set(str(count)+" Parkings")
		# activation du bouton ParkingChoice rattaché
		self.stayParkinkChoiceBt.config(state=NORMAL)
		# Affichage de la présence de Resident lié a ce séjour
		self.resultResident = Resident.select(Resident.q.stay==self.selectedStay)
		count=0
		for row in self.resultResident:
			count+=1
		if count < 2:
			self.stayValues[12].set(str(count)+" Personne")
		else:
			self.stayValues[12].set(str(count)+" Personnes")
		# activation du bouton Resident rattaché
		self.stayResidentBt.config(state=NORMAL)
		# Affichage de la présence de StayBill lié a ce séjour
		self.resultStayBill = StayBill.select(StayBill.q.stay==self.selectedStay)
		count=0
		for row in self.resultStayBill:
			count+=1
		if count < 2:
			self.stayValues[13].set(str(count)+" Facture")
		else:
			self.stayValues[13].set(str(count)+" Factures")
		# activation du bouton StayBill rattaché
		self.stayStayOrderBt.config(state=NORMAL)
		# activation du bouton supprimer
		self.deleteStayBt.config(state=NORMAL)
		# activation du bouton imprimer
		self.printBt.config(state=NORMAL)

	def setDateTime(self, e):
		self.stayValues[2].set(e.date)

	def selectStay(self, event):
		if self.listStay.get(0)!="":
			result = Stay.select(Stay.q.id==self.idListStay[int(self.listStay.curselection()[0])])
			for row in result:
				self.selectedStay = row
			self.listObject[0]=self.selectedStay.contact
			self.listObject[1]=self.selectedStay.discount
			self.listObject[2]=self.selectedStay
			self.stayValues[1].set(self.listObject[0].fname+" - "+self.listObject[0].lname)
			if self.listObject[1] != None:self.stayValues[6].set(self.listObject[1].code)
			if self.selectedStay.voucher != None:self.stayValues[0].set(self.selectedStay.voucher)
			if self.selectedStay.notes != None:self.stayValues[8].set(self.selectedStay.notes)
			if self.selectedStay.checkIn != None:
				# Affichage de la date de Début (self.selectedStay .dateIn)
				self.stayValues[2].set(self.selectedStay.checkIn.strftime("%d/%m/%Y"))
				# Affichage de l'heure de Début dans la ComboBox 
				count = 0
				for h in self.hoursListCB:
					if h == self.selectedStay.checkIn.strftime("%H"): self.hourInStayCB.selectitem(count)
					count+=1
				# Affichage des minutes de Début dans la ComboBox
				count = 0
				for m in self.minutesListCB:
					if m == self.selectedStay.checkIn.strftime("%M"): self.minInStayCB.selectitem(count)
					count+=1
				# Mise à jour des variables heure et minutes de Début
				self.stayHourIn.set(self.selectedStay.checkIn.strftime("%H"))
				self.stayMinuteIn.set(self.selectedStay.checkIn.strftime("%M"))
			if self.selectedStay.checkOut != None:
				# Affichage de la date de Fin (self.selectedStay .dateOut)
				self.stayValues[4].set(self.selectedStay.checkOut.strftime("%d/%m/%Y"))
				# Affichage de l'heure de Fin dans la ComboBox 
				count = 0
				for h in self.hoursListCB:
					if h == self.selectedStay.checkOut.strftime("%H"): self.hourOutStayCB.selectitem(count)
					count+=1
				# Affichage des minutes de Fin dans la ComboBox
				count = 0
				for m in self.minutesListCB:
					if m == self.selectedStay.checkOut.strftime("%M"): self.minOutStayCB.selectitem(count)
					count+=1
				# Mise à jour des variables heure et minutes de Fin
				self.stayHourOut.set(self.selectedStay.checkOut.strftime("%H"))
				self.stayMinuteOut.set(self.selectedStay.checkOut.strftime("%M"))
			# Affichage du Type dans la ComboBox
			status = ((u"O", 0),(u"R", 1),(u"F", 2),(u"A", 3),)
			for n in status:
				if n[0] == self.selectedStay.status: self.stayStatusCB.selectitem(n[1])
			# Affichage de la présence de produits lié a ce séjour
			self.resultProduct = ProductChoice.select(ProductChoice.q.stay==self.selectedStay)
			count=0
			for row in self.resultProduct:
				count+=1
			if count < 2:
				self.stayValues[9].set(str(count)+" Produit")
			else:
				self.stayValues[9].set(str(count)+" Produits")
			# activation du bouton ProductChoice rattaché
			self.stayProductChoiceBt.config(state=NORMAL)
			# Affichage de la présence de Service lié a ce séjour
			self.resultService = ServiceChoice.select(ServiceChoice.q.stay==self.selectedStay)
			count=0
			for row in self.resultService:
				count+=1
			if count < 2:
				self.stayValues[10].set(str(count)+" Service")
			else:
				self.stayValues[10].set(str(count)+" Services")
			# activation du bouton ServiceChoice rattaché
			self.stayServiceChoiceBt.config(state=NORMAL)
			# Affichage de la présence de ParkingChoice lié a ce séjour
			self.resultParking = ParkingChoice.select(ParkingChoice.q.stay==self.selectedStay)
			count=0
			for row in self.resultParking:
				count+=1
			if count < 2:
				self.stayValues[11].set(str(count)+" Parking")
			else:
				self.stayValues[11].set(str(count)+" Parkings")
			# activation du bouton ParkingChoice rattaché
			self.stayParkinkChoiceBt.config(state=NORMAL)
			# Affichage de la présence de Resident lié a ce séjour
			self.resultResident = Resident.select(Resident.q.stay==self.selectedStay)
			count=0
			for row in self.resultResident:
				count+=1
			if count < 2:
				self.stayValues[12].set(str(count)+" Personne")
			else:
				self.stayValues[12].set(str(count)+" Personnes")
			# activation du bouton Resident rattaché
			self.stayResidentBt.config(state=NORMAL)
			# Affichage de la présence de StayBill lié a ce séjour
			self.resultStayBill = StayBill.select(StayBill.q.stay==self.selectedStay)
			count=0
			for row in self.resultStayBill:
				count+=1
			if count < 2:
				self.stayValues[13].set(str(count)+" Facture")
			else:
				self.stayValues[13].set(str(count)+" Factures")
			# activation du bouton StayBill rattaché
			self.stayStayOrderBt.config(state=NORMAL)
			# activation du bouton supprimer
			self.deleteStayBt.config(state=NORMAL)
			# activation du bouton imprimer
			self.printBt.config(state=NORMAL)

	def searchStay(self, event=None):
		if self.searchStayValue.get() != "":
			self.listStay.delete(0,END)
			self.idListStay = []
			result = Stay.select(Stay.q.voucher.startswith(self.searchStayValue.get().encode("utf-8")), orderBy=Stay.q.checkIn)
			for row in result:
				self.listStay.insert(END, row.contact.lname+" - "+row.contact.fname+" du "+row.checkIn.strftime("%d/%m/%Y %H:%M")+" au "+row.checkOut.strftime("%d/%m/%Y %H:%M"))
				self.idListStay.append(row.id)
		else:
			self.listStay.delete(0,END)
			self.idListStay = []
			result = Stay.select(orderBy=Stay.q.checkIn)
			for row in result:
				self.listStay.insert(END, row.contact.lname+" - "+row.contact.fname+" du "+row.checkIn.strftime("%d/%m/%Y %H:%M")+" au "+row.checkOut.strftime("%d/%m/%Y %H:%M"))
				self.idListStay.append(row.id)

	def makeStay(self):
		leftFrame = Frame(self)
		# Fiche Stay  (présentation colonne de gauche)
		Label(leftFrame, text=u"Résérvation").pack(side=TOP, fill=X)
		# Création des champs a renseigner pour un object Stay
		stayStatusListCB= (u"Option",u"Résérvé", u"Ferme", u"Annulé")
		stayLabels = (u"Numéro de voucher", u"Contact", u"Arrivée (date)", u"Arrivée (heure)", u"Départ (date)", u"Départ (heure)", u"Code remise", u"Etat", u"Notes", u"Produits choisi", u"Services choisi", u"Parking choisi", u"Résidents rattachés", u"Factures rattachées")
		self.stayValues = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
		count = 0
		for name in stayLabels:
			f = Frame(leftFrame)
			Label(f, width=18, text=name, anchor=W).pack(side=LEFT)
			if count == 1: # Contact (Person)
				Entry(f, textvariable=self.stayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myPerson=Button(f, image=self.imgSearch, command=lambda x=self.stayValues[count]:self.ctrlListPerson(x), padx=4, pady=1)
				myPerson.pack(side=RIGHT)
				self.balloon.bind(myPerson, u"Séléctionner un Contact")
			elif count == 2: # Date de Arrivée
				Entry(f, textvariable=self.stayValues[count], width=21).pack(side=LEFT, fill=X)
				myCal1=Button(f, image=self.imgCalendar, command=lambda x=self.stayValues[count]:self.ctrlCalendar(x), padx=4, pady=1)
				myCal1.pack(side=LEFT)
				self.balloon.bind(myCal1, u"Calendrier")
			elif count == 3: # Heure de Arrivée
				hStartLb1=Label(f, width=2, text="H", anchor=W)
				hStartLb1.pack(side=LEFT)
				self.balloon.bind(hStartLb1, u"Heure")
				self.hourInStayCB=Pmw.ComboBox(f, selectioncommand=self.stayHourIn, scrolledlist_items=self.hoursListCB, listheight=100)
				self.hourInStayCB._entryfield._entryFieldEntry.config( width = 3)
				self.hourInStayCB.pack(side=LEFT)
				mStartLb1=Label(f, width=3, text="mn", anchor=W)
				mStartLb1.pack(side=LEFT)
				self.balloon.bind(mStartLb1, u"minutes")
				self.minInStayCB=Pmw.ComboBox(f, selectioncommand=self.stayMinuteIn, scrolledlist_items=self.minutesListCB, listheight=100)
				self.minInStayCB._entryfield._entryFieldEntry.config( width = 3)
				self.minInStayCB.pack(side=LEFT)
				# Menu Time
				myTime1=Button(f, image=self.imgTime, padx=1, pady=1)
				myTime1.pack(side=RIGHT)
				myTime1.bind("<ButtonRelease-1>",self.ctrlTimeNow1)
				self.balloon.bind(myTime1, u"Séléctionner une heure")
			elif count == 4: # Date de Départ
				Entry(f, textvariable=self.stayValues[count], width=21).pack(side=LEFT, fill=X)
				myCal2=Button(f, image=self.imgCalendar, command=lambda x=self.stayValues[count]:self.ctrlCalendar(x), padx=4, pady=1)
				myCal2.pack(side=LEFT)
				self.balloon.bind(myCal2, u"Calendrier")
			elif count == 5: # Heure de Départ
				hStartLb2=Label(f, width=2, text="H", anchor=W)
				hStartLb2.pack(side=LEFT)
				self.balloon.bind(hStartLb2, u"Heure")
				self.hourOutStayCB=Pmw.ComboBox(f, selectioncommand=self.stayHourOut, scrolledlist_items=self.hoursListCB, listheight=100)
				self.hourOutStayCB._entryfield._entryFieldEntry.config( width = 3)
				self.hourOutStayCB.pack(side=LEFT, fill=X)
				mStartLb2=Label(f, width=3, text="mn", anchor=W)
				mStartLb2.pack(side=LEFT)
				self.balloon.bind(mStartLb2, u"minutes")
				self.minOutStayCB=Pmw.ComboBox(f, selectioncommand=self.stayMinuteOut, scrolledlist_items=self.minutesListCB, listheight=100)
				self.minOutStayCB._entryfield._entryFieldEntry.config( width = 3)
				self.minOutStayCB.pack(side=LEFT, fill=X) 
				# Menu Time
				myTime2=Button(f, image=self.imgTime, padx=1, pady=1)
				myTime2.pack(side=RIGHT)
				myTime2.bind("<ButtonRelease-1>",self.ctrlTimeNow2)
				self.balloon.bind(myTime2, u"Séléctionner une heure")
			elif count == 6: # Remise (Discount)
				Entry(f, textvariable=self.stayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myDiscount=Button(f, image=self.imgSearch, command=lambda x=self.stayValues[count]:self.ctrlListDiscount(x), padx=4, pady=1)
				myDiscount.pack(side=RIGHT)
				self.balloon.bind(myDiscount, u"Séléctionner une Remise")
			elif count == 7: # Status
				self.stayStatusCB=Pmw.ComboBox(f, selectioncommand=self.stayStatus, scrolledlist_items=stayStatusListCB, listheight=100)
				self.stayStatusCB._entryfield._entryFieldEntry.config( width=21)
				self.stayStatusCB.pack(side=LEFT, fill=X)
				self.stayStatusCB.selectitem(0)
				self.stayValues[count].set(u"O")
			elif count == 8: # Notes
				Entry(f, textvariable=self.stayValues[count], width=21).pack(side=LEFT, fill=X)
				myNotes=Button(f, image=self.imgNotes, command=lambda x=self.stayValues[count]:self.ctrlNotes(x,u"Notes"), padx=4, pady=1)
				myNotes.pack(side=RIGHT)
				self.balloon.bind(myNotes, u"Détails de la note")
			elif count == 9: # ProductChoice
				Entry(f, textvariable=self.stayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				self.stayProductChoiceBt=Button(f, image=self.imgLinks, command=lambda x=self.stayValues[count]:self.ctrlProductChoice(x), padx=4, pady=1, state=DISABLED)
				self.balloon.bind(self.stayProductChoiceBt, u"Choisir un ou plusieurs produits pour ce séjour.\nCommencer par créer un séjour puis séléctionner le dans la\nliste pour pouvoir résérver des produit.")
				self.stayProductChoiceBt.pack(side=RIGHT)
			elif count == 10: # ServiceChoice
				Entry(f, textvariable=self.stayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				self.stayServiceChoiceBt=Button(f, image=self.imgLinks, command=lambda x=self.stayValues[count]:self.ctrlServiceChoice(x), padx=4, pady=1, state=DISABLED)
				self.balloon.bind(self.stayServiceChoiceBt, u"Choisir un ou plusieurs services pour ce séjour.\nCommencer par créer un séjour puis séléctionner le dans la\nliste pour pouvoir résérver des services liés.")
				self.stayServiceChoiceBt.pack(side=RIGHT)
			elif count == 11: # ParkinkChoice
				Entry(f, textvariable=self.stayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				self.stayParkinkChoiceBt=Button(f, image=self.imgLinks, command=lambda x=self.stayValues[count]:self.ctrlParkingChoice(x), padx=4, pady=1, state=DISABLED)
				self.balloon.bind(self.stayParkinkChoiceBt, u"Choisir une ou plusieurs place de parking pour ce séjour.\nCommencer par créer un séjour puis séléctionner le dans la\nliste pour pouvoir résérver des places de parking.")
				self.stayParkinkChoiceBt.pack(side=RIGHT)
			elif count == 12: # Resident
				Entry(f, textvariable=self.stayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				self.stayResidentBt=Button(f, image=self.imgLinks, command=lambda x=self.stayValues[count]:self.ctrlResident(x), padx=4, pady=1, state=DISABLED)
				self.balloon.bind(self.stayResidentBt, u"Ajouter ou supprimer les participant à ce séjour.\nCommencer par créer un séjour puis séléctionner le dans la\nliste pour pouvoir lui ajouter des participants liés.")
				self.stayResidentBt.pack(side=RIGHT)
			elif count == 13: # StayOrder
				Entry(f, textvariable=self.stayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				self.stayStayOrderBt=Button(f, image=self.imgLinks, command=lambda x=self.stayValues[count]:self.ctrlStayBill(x), padx=4, pady=1, state=DISABLED)
				self.balloon.bind(self.stayStayOrderBt, u"Factures liées à ce séjour.\nCommencer par créer un séjour puis séléctionner le dans la\nliste pour pouvoir visualisé les factures liés.")
				self.stayStayOrderBt.pack(side=RIGHT)
			else: 
				Entry(f, textvariable=self.stayValues[count], width=24).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveStayBt=Button(s, image=self.imgSave, command=self.createStay)
		self.saveStayBt.bind("<Return>", self.createStay)
		self.saveStayBt.pack(side=LEFT)
		self.balloon.bind(self.saveStayBt, u"Enregistrer")
		self.deleteStayBt=Button(s, image=self.imgDelete, command=self.deleteStay, state=DISABLED)
		self.deleteStayBt.bind("<Return>", self.deleteStay)
		self.deleteStayBt.pack(side=LEFT)
		self.balloon.bind(self.deleteStayBt, u"Supprimer")
		self.printBt=Button(s, image=self.imgPrint, command=self.printStay, state=DISABLED)
		self.printBt.bind("<Return>", self.printStay)
		self.printBt.pack(side=RIGHT, fill=X)
		self.balloon.bind(self.printBt, u"Imprimer(PDF)")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Liste des Stay existants (présentation colonne de droite)
		rightFrame = Frame(self) 
		Label(rightFrame, text=u"Liste des Réservations").pack(side=TOP, fill=X)
		self.searchStayValue = StringVar()
		self.searchStayEt = Entry(rightFrame,  width=63, textvariable=self.searchStayValue, relief=GROOVE)
		self.searchStayEt.bind("<KeyRelease>", self.searchStay)
		self.searchStayEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchStayEt, u"Saisir les premières lettres d'une Résérvation\npour une recherche plus précise,\nla liste est classée par date de début.")
		s = Frame(rightFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listStay = Listbox(s)
		self.listStay.config(yscrollcommand=scrollbar.set, width=60, selectmode=SINGLE, height=18)
		self.listStay.bind("<ButtonRelease-1>",self.selectStay)
		scrollbar.config(command=self.listStay.yview)
		self.listStay.pack()
		self.balloon.bind(self.listStay, u"Séléctionner une Résérvation\npour la visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		rightFrame.pack(side=RIGHT, fill=BOTH)
		# Initialisation
		self.clearFieldStay()
		self.searchStay()

	def ctrlTimeNow1(self,event):
		varHour=[self.stayHourIn, self.stayMinuteIn, self.hourInStayCB, self.minInStayCB] 
		TimePopupGUI(self, event=event, field=self.stayValues[3], varHour=varHour, log=self.log, path=self.path)

	def ctrlTimeNow2(self,event):
		varHour=[self.stayHourOut, self.stayMinuteOut, self.hourOutStayCB, self.minOutStayCB]
		TimePopupGUI(self, event=event, field=self.stayValues[5], varHour=varHour, log=self.log, path=self.path)

	def ctrlCalendar(self,field):
		CalendarGUI(field=field, log=self.log, path=self.path)

	def ctrlNotes(self,field,title):
		NotesGUI(field=field,title=title, log=self.log, path=self.path)

	def ctrlListPerson(self,field): # index 0
		PersonListGUI(balloon=self.balloon, field=field, index=0, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlListDiscount(self,field): # index 1
		DiscountListGUI(balloon=self.balloon, field=field, index=1, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlProductChoice(self,field): # index 2
		ProductChoiceGUI(balloon=self.balloon, field=field, index=2, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlServiceChoice(self,field): # index 2
		ServiceChoiceGUI(balloon=self.balloon, field=field, index=2, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlParkingChoice(self,field): # index 2
		ParkingChoiceGUI(balloon=self.balloon, field=field, index=2, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlResident(self,field): # index 2
		ResidentGUI(balloon=self.balloon, field=field, index=2, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlStayBill(self,field): # index 2
		StayBillGUI(balloon=self.balloon, field=field, index=2, listObject=self.listObject, log=self.log, path=self.path)

	def stayStatus(self, value):
		status = ((u"O", u"Option"),(u"R", u"Résérvé"),(u"F", u"Ferme"),(u"A", u"Annulé"),)
		for n in status:
			if n[1] == value: self.stayValues[7].set(n[0])

	def stayHourIn(self, value):
		self.stayHourIn.set(value)
		self.minInStayCB.selectitem(0)
		self.minInStayCB.invoke()

	def stayMinuteIn(self, value):
		self.stayMinuteIn.set(value)

	def stayHourOut(self, value):
		self.stayHourOut.set(value)
		self.minOutStayCB.selectitem(0)
		self.minOutStayCB.invoke()

	def stayMinuteOut(self, value):
		self.stayMinuteOut.set(value)

	def getDateTimeInStay(self):
		if self.stayValues[2].get() != "":
			date=self.stayValues[2].get().split("/")
			d = datetime.datetime(int(date[2]), int(date[1]), int(date[0]), int(self.stayHourIn.get()), int(self.stayMinuteIn.get()), 0)
			return d
		else:
			return None

	def getDateTimeOutStay(self):
		if self.stayValues[4].get() != "":
			date=self.stayValues[4].get().split("/")
			d = datetime.datetime(int(date[2]), int(date[1]), int(date[0]), int(self.stayHourOut.get()), int(self.stayMinuteOut.get()), 0)
			return d
		else:
			return None

	def verifyStay(self):
		if self.stayValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Voucher est obligatoire !\nMerci de le compléter.")
			return False
		elif self.stayValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Contact est obligatoire !\nMerci de le compléter.")
			return False
		elif self.stayValues[2].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Date d'arrivée est obligatoire !\nMerci de le compléter.")
			return False
		elif self.stayValues[4].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Date de départ est obligatoire !\nMerci de le compléter.")
			return False
		elif self.stayHourIn.get() == "" or  self.stayMinuteIn.get() == "": # TODO Créer une fonction validTime()
			showerror(u"Erreur de saisie", u"Les champs Heures et Minutes d'arrivée sont obligatoire !\nMerci de les compléter.")
			return False
		elif self.stayHourOut.get() == "" or  self.stayMinuteOut.get() == "": # TODO Créer une fonction validTime()
			showerror(u"Erreur de saisie", u"Les champs Heures et Minutes de départ sont obligatoire !\nMerci de les compléter.")
			return False
		else:
			return True

	def createStay(self, event=None):
		if self.verifyStay():
			if  self.deleteStayBt.config()["state"][4] == "normal":
				self.modifyStay()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer une nouvelle Résérvation du %s au %s ?\n" % (self.stayValues[2].get(), self.stayValues[4].get()) ):
					Stay(contact=self.listObject[0],
						discount=self.listObject[1],
						checkIn=self.getDateTimeInStay(),
						checkOut=self.getDateTimeOutStay(),
						voucher=self.stayValues[0].get().encode("utf-8"),
						status=self.stayValues[7].get().encode("utf-8"),
						notes=self.stayValues[8].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchStay()
				self.clearFieldStay()

	def modifyStay(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier la Résérvation numéro %s de %s %s du %s au %s ?" % (self.selectedStay.id, self.selectedStay.contact.lname, self.selectedStay.contact.fname, self.selectedStay.checkIn.strftime("%d/%m/%Y"), self.selectedStay.checkOut.strftime("%d/%m/%Y"))):
			self.selectedStay.contact=self.listObject[0]
			self.selectedStay.discount=self.listObject[1]
			self.selectedStay.checkIn=self.getDateTimeInStay()
			self.selectedStay.checkOut=self.getDateTimeOutStay()
			self.selectedStay.voucher=self.stayValues[0].get().encode("utf-8")
			self.selectedStay.status=self.stayValues[7].get().encode("utf-8")
			self.selectedStay.notes=self.stayValues[8].get().encode("utf-8")
			self.searchStay()
		self.deleteStayBt.config(state=DISABLED)
		# desactivation du bouton imprimer
		self.printBt.config(state=DISABLED)
		self.clearFieldStay()

	def deleteStay(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer la Résérvation numéro %s de %s %s du %s au %s ?\nCette opération est irréversible !" % (self.selectedStay.id, self.selectedStay.contact.lname, self.selectedStay.contact.fname, self.selectedStay.checkIn.strftime("%d/%m/%Y"), self.selectedStay.checkOut.strftime("%d/%m/%Y"))):
			Stay.delete(self.selectedStay.id)
			self.searchStay()            
		self.deleteStayBt.config(state=DISABLED)
		# desactivation du bouton imprimer
		self.printBt.config(state=DISABLED)
		self.clearFieldStay()
		
	def printStay(self, event=None):
		pdf=StayPDF(path=self.path, log=self.log, stay=self.selectedStay, products=self.resultProduct, services=self.resultService, parkings=self.resultParking, residents=self.resultResident, bills=self.resultStayBill)
		if pdf.check == 1:
			showinfo(u"Success", u"Le fichier PDF est disponible dans le répertoire pdf")
		else:
			showerror(u"Erreur", u"Une erreur à empècher la création du fichier PDF !")
	
	# FIN de la gestion du module Stay ------------------------------------------------------------------------------------------------------------------------

class StayListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des Séjours")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Reservation-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Reservation-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tStayListGUI\tStart")
		self.makeListStay()

	def selectListStay(self, event):
		if self.listListStay.get(0)!="":
			result = Stay.select(Stay.q.id==self.idListListStay[int(self.listListStay.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row.voucher+" - "+row.contact.lname)
				self.destroy()

	def searchListStay(self, event=None):
		if self.searchListStayValue.get() != "":
			self.listListStay.delete(0,END)
			self.idListListStay = []
			result = Stay.select(Stay.q.voucher.startswith(self.searchListStayValue.get().encode("utf-8")), orderBy=Stay.q.checkIn)
			for row in result:
				self.listListStay.insert(END, row.voucher+" - "+row.contact.lname)
				self.idListListStay.append(row.id)
		else:
			self.listListStay.delete(0,END)
			self.idListListStay = []
			result = Stay.select(orderBy=Stay.q.checkIn)
			for row in result:
				self.listListStay.insert(END, row.voucher+" - "+row.contact.lname)
				self.idListListStay.append(row.id)

	def makeListStay(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste des Séjours").pack(side=TOP, fill=X)
		self.searchListStayValue = StringVar()
		s = Frame(leftFrame) 
		self.searchListStayEt = Entry(s,  width=32, textvariable=self.searchListStayValue, relief=GROOVE)
		self.searchListStayEt.bind("<KeyRelease>", self.searchListStay)
		self.searchListStayEt.pack(side=LEFT, fill=X)
		self.balloon.bind(self.searchListStayEt, u"Saisir les premiéres lettres du numero de Voucher d'un Séjour\npour une recherche plus précise,\nla liste est classée par Date d'arrivée.")
		newStay=Button(s, image=self.imgNew, command=self.ctrlStay)
		newStay.pack(side=RIGHT)
		self.balloon.bind(newStay, u"Créer un nouveau Séjour")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListStay = Listbox(s)
		self.listListStay.config(yscrollcommand=scrollbar.set,width=33, selectmode=SINGLE, height=16)
		self.listListStay.bind("<ButtonRelease-1>",self.selectListStay)
		scrollbar.config(command=self.listListStay.yview)
		self.listListStay.pack()
		self.balloon.bind(self.listListStay, u"Séléctionner un Séjour.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListStay()

	def ctrlStay(self):
		StayGUI(balloon=self.balloon, log=self.log, path=self.path)

class ProductChoiceGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Choix des Produits")
		self.balloon=balloon
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Product-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Product-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tProductChoiceGUI\tStart")
		self.makeProductChoice()

	# DEBUT de la gestion du module ProductChoice ------------------------------------------------------------------------------------------------------------------
	def clearFieldProductChoice(self):
		# Mise a zéro des champs
		self.productChoiceValues[1].set("")
		self.listObjectPC=[Place,Product]
		# Affichage du nombre de produits rattaché à ce séjour
		result = ProductChoice.select(ProductChoice.q.stay==self.listObject[self.index])
		count=0
		for row in result:
			count+=1
		if count < 2:
			self.field.set(str(count)+" Produit")
		else:
			self.field.set(str(count)+" Produits")

	def selectProductChoice(self, event):
		if self.listProductChoice.get(0)!="":
			result = ProductChoice.select(ProductChoice.q.id==self.idListProductChoice[int(self.listProductChoice.curselection()[0])])
			for row in result:
				self.selectedProductChoice = row
			self.listObjectPC[1]=self.selectedProductChoice.wish
			if self.selectedProductChoice.wish != None:self.productChoiceValues[1].set(self.selectedProductChoice.wish)
			# activation du bouton supprimer
			self.deleteProductChoiceBt.config(state=NORMAL)

	def searchProductChoice(self, event=None):
		self.listProductChoice.delete(0,END)
		self.idListProductChoice = []
		result = ProductChoice.select(ProductChoice.q.stay==self.listObject[self.index],orderBy=ProductChoice.q.id)
		for row in result:
			self.listProductChoice.insert(END, str(row.id)+" - "+row.wish.designation+" - "+row.wish.place.company)
			self.idListProductChoice.append(row.id)

	def makeProductChoice(self,field=None,index=None):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Produit").pack(side=TOP, fill=X)
		productChoiceLabels = (u"Séjour", u"Produit")
		self.productChoiceValues = [StringVar(),StringVar()]
		count = 0
		for name in productChoiceLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Séjour
				Entry(f, textvariable=self.productChoiceValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			else: # Produit
				Entry(f, textvariable=self.productChoiceValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myProduct=Button(f, image=self.imgSearch, command=lambda x=self.productChoiceValues[count]:self.ctrlListProduct(x), padx=4, pady=1)
				myProduct.pack(side=RIGHT)
				self.balloon.bind(myProduct, u"Séléctionner un Produit")
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveProductChoiceBt=Button(s, image=self.imgSave, command=self.createProductChoice)
		self.saveProductChoiceBt.bind("<Return>", self.createProductChoice)
		self.saveProductChoiceBt.pack(side=LEFT)
		self.balloon.bind(self.saveProductChoiceBt, u"Enregistrer")
		self.deleteProductChoiceBt=Button(s, image=self.imgDelete, command=self.deleteProductChoice, state=DISABLED)
		self.deleteProductChoiceBt.bind("<Return>", self.deleteProductChoice)
		self.deleteProductChoiceBt.pack(side=LEFT)
		self.balloon.bind(self.deleteProductChoiceBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		# Liste des Produits Choisi (présentation colonne de droite)
		Label(leftFrame, text=u"Liste des Produits séléctionnés").pack(side=TOP, fill=X)
		s = Frame(leftFrame)
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listProductChoice = Listbox(s)
		self.listProductChoice.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=10)
		self.listProductChoice.bind("<ButtonRelease-1>",self.selectProductChoice)
		scrollbar.config(command=self.listProductChoice.yview)
		self.listProductChoice.pack(side=TOP, fill=X)
		self.balloon.bind(self.listProductChoice, u"Séléctionner un Produit Choisi\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.listObjectPC=[Place,Product]
		self.productChoiceValues[0].set("ID:"+str(self.listObject[self.index].id)+" "+self.listObject[self.index].contact.lname)
		self.searchProductChoice()

	def ctrlListProduct(self,field):
		ProductListGUI(balloon=self.balloon, field=field, index=1, indexPlace=0, listObject=self.listObjectPC, log=self.log, path=self.path)

	def verifyProductChoice(self):
		if self.productChoiceValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Produit est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createProductChoice(self, event=None):
		if self.verifyProductChoice():
			if  self.deleteProductChoiceBt.config()["state"][4] == "normal":
				self.modifyProductChoice()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouveau Choix de produit ?\n" % self.productChoiceValues[1].get()):
					ProductChoice(stay=self.listObject[self.index],
						wish=self.listObjectPC[1],
						createDate=datetime.datetime.now()
					)
					self.searchProductChoice()
				self.clearFieldProductChoice()

	def modifyProductChoice(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le Choix du Produit %s ?" % self.selectedProductChoice.wish):
			self.selectedProductChoice.wish=self.listObjectPC[1]   
			self.searchProductChoice()
		self.deleteProductChoiceBt.config(state=DISABLED)
		self.clearFieldProductChoice()

	def deleteProductChoice(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer le Choix du Produit %s ?\nCette opération est irréversible !" % self.selectedProductChoice.wish):
			ProductChoice.delete(self.selectedProductChoice.id)
			self.searchProductChoice()            
		self.deleteProductChoiceBt.config(state=DISABLED)
		self.clearFieldProductChoice()
	# FIN de la gestion du module ProductChoice ----------------------------------------------------------------------------------------------------------

class ParkingChoiceGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Choix des Parking")
		self.balloon=balloon
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Parking-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Parking-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tParkingChoiceGUI\tStart")
		self.makeParkingChoice()

	# DEBUT de la gestion du module ParkingChoice -----------------------------------------------------------------------------------------------
	def clearFieldParkingChoice(self):
		# Mise a zéro des champs
		self.parkingChoiceValues[1].set("")
		self.parkingChoiceTypeCB.selectitem(0)
		self.parkingChoiceValues[2].set(u"A")
		self.listObjectPC=[Place,Parking]
		# Affichage du nombre de Parking rattaché à ce séjour
		result = ParkingChoice.select(ParkingChoice.q.stay==self.listObject[self.index])
		count=0
		for row in result:
			count+=1
		if count < 2:
			self.field.set(str(count)+" Parking")
		else:
			self.field.set(str(count)+" Parkings")

	def selectParkingChoice(self, event):
		if self.listParkingChoice.get(0)!="":
			result = ParkingChoice.select(ParkingChoice.q.id==self.idListParkingChoice[int(self.listParkingChoice.curselection()[0])])
			for row in result:
				self.selectedParkingChoice = row
			self.listObjectPC[1]=self.selectedParkingChoice.wish
			if self.selectedParkingChoice.wish != None:self.parkingChoiceValues[1].set(self.selectedParkingChoice.wish)
			if self.selectedParkingChoice.type != None:self.parkingChoiceValues[2].set(self.selectedParkingChoice.type)
			# Affichage du Type dans la ComboBox
			type = (("A", 0),("B", 1), ("O", 2), ("X", 3), ("N", 4), ("M", 5), ("S", 6),)
			for n in type:
				if n[0] == self.selectedParkingChoice.type: self.parkingChoiceTypeCB.selectitem(n[1])
			# activation du bouton supprimer
			self.deleteParkingChoiceBt.config(state=NORMAL)

	def searchParkingChoice(self, event=None):
		self.listParkingChoice.delete(0,END)
		self.idListParkingChoice = []
		result = ParkingChoice.select(ParkingChoice.q.stay==self.listObject[self.index],orderBy=ParkingChoice.q.id)
		for row in result:
			self.listParkingChoice.insert(END, str(row.id)+" - "+row.wish.description+" - "+row.wish.place.company)
			self.idListParkingChoice.append(row.id)

	def makeParkingChoice(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Parking").pack(side=TOP, fill=X)
		parkingChoiceLabels = (u"Séjour", u"Parking", u"Type de véhicul")
		self.parkingChoiceValues = [StringVar(),StringVar(),StringVar()]
		parkingTypeListCB = ("Aucun", "Berline", "Moto", "4x4", "Monospace", "Mini bus", "Bus")
		count = 0
		for name in parkingChoiceLabels:
			f = Frame(leftFrame)
			Label(f, width=18, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Séjour
				Entry(f, textvariable=self.parkingChoiceValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			elif count == 2: # Type de vehicul
				self.parkingChoiceTypeCB=Pmw.ComboBox(f, selectioncommand=self.parkingChoiceType, scrolledlist_items=parkingTypeListCB, listheight=140)
				self.parkingChoiceTypeCB._entryfield._entryFieldEntry.config( width=21)
				self.parkingChoiceTypeCB.pack(side=LEFT, fill=X)
				self.parkingChoiceTypeCB.selectitem(0)
				self.parkingChoiceValues[count].set(u"A")
			else: 
				Entry(f, textvariable=self.parkingChoiceValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myParking=Button(f, image=self.imgSearch, command=lambda x=self.parkingChoiceValues[count]:self.ctrlListParking(x), padx=4, pady=1)
				myParking.pack(side=RIGHT)
				self.balloon.bind(myParking, u"Séléctionner un Parking")                
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveParkingChoiceBt=Button(s, image=self.imgSave, command=self.createParkingChoice)
		self.saveParkingChoiceBt.bind("<Return>", self.createParkingChoice)
		self.saveParkingChoiceBt.pack(side=LEFT)
		self.balloon.bind(self.saveParkingChoiceBt, u"Enregistrer")
		self.deleteParkingChoiceBt=Button(s, image=self.imgDelete, command=self.deleteParkingChoice, state=DISABLED)
		self.deleteParkingChoiceBt.bind("<Return>", self.deleteParkingChoice)
		self.deleteParkingChoiceBt.pack(side=LEFT)
		self.balloon.bind(self.deleteParkingChoiceBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des Parking séléctionnés").pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listParkingChoice = Listbox(s)
		self.listParkingChoice.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=10)
		self.listParkingChoice.bind("<ButtonRelease-1>",self.selectParkingChoice)
		scrollbar.config(command=self.listParkingChoice.yview)
		self.listParkingChoice.pack(side=TOP, fill=X)
		self.balloon.bind(self.listParkingChoice, u"Séléctionner un Parking Choisi\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.listObjectPC=[Place,Parking]
		self.parkingChoiceValues[0].set("ID:"+str(self.listObject[self.index].id)+" "+self.listObject[self.index].contact.lname)
		#~ self.searchListParkingPC()
		self.searchParkingChoice()

	def ctrlListParking(self,field):
		ParkingListGUI(balloon=self.balloon, field=field, index=1, indexPlace=0, listObject=self.listObjectPC, log=self.log, path=self.path)

	def parkingChoiceType(self, value):
		type = (("A", "Aucun"),("B", "Berline"), ("O", "Moto"), ("X", "4x4"), ("N", "Monospace"), ("M", "Mini bus"), ("S", "Bus"),)
		for n in type:
			if n[1] == value: self.parkingChoiceValues[2].set(n[0])

	def verifyParkingChoice(self):
		if self.parkingChoiceValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Parking est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createParkingChoice(self, event=None):
		if self.verifyParkingChoice():
			if  self.deleteParkingChoiceBt.config()["state"][4] == "normal":
				self.modifyParkingChoice()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouveau Choix de Parking ?\n" % self.parkingChoiceValues[1].get()):
					ParkingChoice(stay=self.listObject[self.index],
						wish=self.listObjectPC[1],
						type=self.parkingChoiceValues[2].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchParkingChoice()
				self.clearFieldParkingChoice()

	def modifyParkingChoice(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le Choix du Parking %s ?" % self.selectedParkingChoice.wish):
			self.selectedParkingChoice.wish=self.listObjectPC[1] 
			self.selectedParkingChoice.type=self.parkingChoiceValues[2].get().encode("utf-8"),
			self.searchParkingChoice()
		self.deleteParkingChoiceBt.config(state=DISABLED)
		self.clearFieldParkingChoice()

	def deleteParkingChoice(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer le Choix du Parking %s ?\nCette opération est irréversible !" % self.selectedParkingChoice.wish):
			ParkingChoice.delete(self.selectedParkingChoice.id)
			self.searchParkingChoice()            
		self.deleteParkingChoiceBt.config(state=DISABLED)
		self.clearFieldParkingChoice()
	# FIN de la gestion du module ParkingChoice ------------------------------------------------------------------------------------------------------

class ServiceChoiceGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Choix des Services")
		self.balloon=balloon
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Service-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Service-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tServiceChoiceGUI\tStart")
		self.makeServiceChoice()

	# DEBUT de la gestion du module ServiceChoice ----------------------------------------------------------------------------------------------
	def clearFieldServiceChoice(self):
		# Mise a zéro des champs
		self.serviceChoiceValues[1].set("")
		self.listObjectSC=[Place,Service]
		# Affichage du nombre de Service rattaché à ce séjour
		result = ServiceChoice.select(ServiceChoice.q.stay==self.listObject[self.index])
		count=0
		for row in result:
			count+=1
		if count < 2:
			self.field.set(str(count)+" Service")
		else:
			self.field.set(str(count)+" Services")

	def selectServiceChoice(self, event):
		if self.listServiceChoice.get(0)!="":
			result = ServiceChoice.select(ServiceChoice.q.id==self.idListServiceChoice[int(self.listServiceChoice.curselection()[0])])
			for row in result:
				self.selectedServiceChoice = row
			self.listObjectSC[1]=self.selectedServiceChoice.wish
			if self.selectedServiceChoice.wish != None:self.serviceChoiceValues[1].set(self.selectedServiceChoice.wish)
			# activation du bouton supprimer
			self.deleteServiceChoiceBt.config(state=NORMAL)

	def searchServiceChoice(self, event=None):
		self.listServiceChoice.delete(0,END)
		self.idListServiceChoice = []
		result = ServiceChoice.select(ServiceChoice.q.stay==self.listObject[self.index],orderBy=ServiceChoice.q.id)
		for row in result:
			self.listServiceChoice.insert(END, str(row.id)+" - "+row.wish.designation+" - "+row.wish.place.company)
			self.idListServiceChoice.append(row.id)

	def makeServiceChoice(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Service", anchor=W).pack(side=TOP, fill=X)
		serviceChoiceLabels = (u"Séjour", u"Service")
		self.serviceChoiceValues = [StringVar(),StringVar()]
		count = 0
		for name in serviceChoiceLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Séjour
				Entry(f, textvariable=self.serviceChoiceValues[count], width=23, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			else: # Service
				Entry(f, textvariable=self.serviceChoiceValues[count], width=23, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myService=Button(f, image=self.imgSearch, command=lambda x=self.serviceChoiceValues[count]:self.ctrlListService(x), padx=4, pady=1)
				myService.pack(side=RIGHT)
				self.balloon.bind(myService, u"Séléctionner un Service") 
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveServiceChoiceBt=Button(s, image=self.imgSave, command=self.createServiceChoice)
		self.saveServiceChoiceBt.bind("<Return>", self.createServiceChoice)
		self.saveServiceChoiceBt.pack(side=LEFT)
		self.balloon.bind(self.saveServiceChoiceBt, u"Enregistrer")
		self.deleteServiceChoiceBt=Button(s, image=self.imgDelete, command=self.deleteServiceChoice, state=DISABLED)
		self.deleteServiceChoiceBt.bind("<Return>", self.deleteServiceChoice)
		self.deleteServiceChoiceBt.pack(side=LEFT)
		self.balloon.bind(self.deleteServiceChoiceBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des Services séléctionnés").pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listServiceChoice = Listbox(s)
		self.listServiceChoice.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=10)
		self.listServiceChoice.bind("<ButtonRelease-1>",self.selectServiceChoice)
		scrollbar.config(command=self.listServiceChoice.yview)
		self.listServiceChoice.pack(side=TOP, fill=X)
		self.balloon.bind(self.listServiceChoice, u"Séléctionner un Service Choisi\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.listObjectSC=[Place,Service]
		self.serviceChoiceValues[0].set("ID:"+str(self.listObject[self.index].id)+" "+self.listObject[self.index].contact.lname)
		self.searchServiceChoice()

	def ctrlListService(self,field):
		ServiceListGUI(balloon=self.balloon, field=field, index=1, indexPlace=0, listObject=self.listObjectSC, log=self.log, path=self.path)

	def verifyServiceChoice(self):
		if self.serviceChoiceValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Service est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createServiceChoice(self, event=None):
		if self.verifyServiceChoice():
			if  self.deleteServiceChoiceBt.config()["state"][4] == "normal":
				self.modifyServiceChoice()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouveau Choix de Service ?\n" % self.serviceChoiceValues[1].get()):
					ServiceChoice(stay=self.listObject[self.index],
						wish=self.listObjectSC[1],
						createDate=datetime.datetime.now()
					)
					self.searchServiceChoice()
				self.clearFieldServiceChoice()

	def modifyServiceChoice(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le Choix du Service %s ?" % self.selectedServiceChoice.wish):
			self.selectedServiceChoice.wish=self.listObjectSC[1]   
			self.searchServiceChoice()
		self.deleteServiceChoiceBt.config(state=DISABLED)
		self.clearFieldServiceChoice()

	def deleteServiceChoice(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer le Choix du Service %s ?\nCette opération est irréversible !" % self.selectedServiceChoice.wish):
			ServiceChoice.delete(self.selectedServiceChoice.id)
			self.searchServiceChoice()            
		self.deleteServiceChoiceBt.config(state=DISABLED)
		self.clearFieldServiceChoice()
	# FIN de la gestion du module ServiceChoice ------------------------------------------------------------------------------------------------------

class ResidentGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Choix des Resident")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.imgNotes=PhotoImage(file="img/edit.gif")
		self.balloon=balloon
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Resident-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Resident-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tResidentGUI\tStart")
		self.makeResident()

	# DEBUT de la gestion du module Resident ---------------------------------------------------------------------------------------------------------
	def clearFieldResident(self):
		# Mise a zéro des champs
		self.residentValues[1].set("")
		self.residentOldCB.selectitem(3)
		self.residentValues[2].set(u"A")
		self.residentValues[3].set("")
		self.residentPetsCB.selectitem(0)
		self.residentValues[4].set(u"NO")
		self.residentValues[5].set("")
		self.listObjectRE=[Place,Person]
		# Affichage du nombre de Parking rattaché à ce séjour
		result = Resident.select(Resident.q.stay==self.listObject[self.index])
		count=0
		for row in result:
			count+=1
		if count < 2:
			self.field.set(str(count)+" Resident")
		else:
			self.field.set(str(count)+" Residents")

	def selectResident(self, event):
		if self.listResident.get(0)!="":
			result = Resident.select(Resident.q.id==self.idListResident[int(self.listResident.curselection()[0])])
			for row in result:
				self.selectedResident = row
			self.listObjectRE[1] = self.selectedResident.person
			if self.selectedResident.person != None:self.residentValues[1].set(self.selectedResident.person.fname+" - "+self.selectedResident.person.lname)
			if self.selectedResident.old != None:self.residentValues[2].set(self.selectedResident.old)
			if self.selectedResident.passport != None:self.residentValues[3].set(self.selectedResident.passport)
			if self.selectedResident.pets != None:self.residentValues[4].set(self.selectedResident.pets)
			if self.selectedResident.notes != None:self.residentValues[5].set(self.selectedResident.notes)
			# Affichage du Old dans la ComboBox
			old = (("B", 0),("K", 1),("T", 2),("A", 3),("M", 4),("O", 5),) 
			for n in old:
				if n[0] == self.selectedResident.old: self.residentOldCB.selectitem(n[1])
			# Affichage du Pets dans la ComboBox
			pets = (("NO", 0),("D1", 1),("D2", 2),("D3",3),("C1",4),("C2", 5),("C3", 6),("O", 7),("R", 8),("A", 9),)
			for n in pets:
				if n[0] == self.selectedResident.pets: self.residentPetsCB.selectitem(n[1])
			# activation du bouton supprimer
			self.deleteResidentBt.config(state=NORMAL)

	def searchResident(self, event=None):
		self.listResident.delete(0,END)
		self.idListResident = []
		result = Resident.select(Resident.q.stay==self.listObject[self.index],orderBy=Resident.q.id)
		for row in result:
			self.listResident.insert(END, str(row.id)+" - "+str(row.person.fname+" - "+row.person.lname))
			self.idListResident.append(row.id)

	def makeResident(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Resident").pack(side=TOP, fill=X)
		residentLabels = (u"Séjour", u"Resident", u"Age", u"Passeport", u"Animeaux", u"Notes")
		self.residentValues = [StringVar(),StringVar(),StringVar(),StringVar(),StringVar(),StringVar()]
		residentPetsListCB = ("Aucun", "1 Chien", "2 Chiens", "3 Chiens", "1 Chat", "2 Chats", "3 Chats", "Oiseau", "Rongeur", "Autre")
		residentOldListCB = ("Baby", "Kid", "Teen", "Adult", "Mature", "Old") 
		count = 0
		for name in residentLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Séjour
				Entry(f, textvariable=self.residentValues[count], width=27, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			elif count == 1: # Résident
				Entry(f, textvariable=self.residentValues[count], width=27, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myPerson=Button(f, image=self.imgSearch, command=lambda x=self.residentValues[count]:self.ctrlListPerson(x), padx=4, pady=1)
				myPerson.pack(side=RIGHT)
				self.balloon.bind(myPerson, u"Choisir un Résident")
			elif count == 2: # Old
				self.residentOldCB=Pmw.ComboBox(f, selectioncommand=self.residentOld, scrolledlist_items=residentOldListCB, listheight=140)
				self.residentOldCB._entryfield._entryFieldEntry.config( width = 27)
				self.residentOldCB.pack(side=LEFT, fill=X)
				self.residentOldCB.selectitem(3)
				self.residentValues[count].set(u"A")
			elif count == 4: # Pets
				self.residentPetsCB=Pmw.ComboBox(f, selectioncommand=self.residentPets, scrolledlist_items=residentPetsListCB, listheight=140)
				self.residentPetsCB._entryfield._entryFieldEntry.config( width = 27)
				self.residentPetsCB.pack(side=LEFT, fill=X)
				self.residentPetsCB.selectitem(0)
				self.residentValues[count].set(u"NO")
			elif count == 5: # Notes
				Entry(f, textvariable=self.residentValues[count], width=27).pack(side=LEFT, fill=X)
				myNotes=Button(f, image=self.imgNotes, command=lambda x=self.residentValues[count]:self.ctrlNotes(x,u"Notes"), padx=4, pady=1)
				myNotes.pack(side=RIGHT)
				self.balloon.bind(myNotes, u"Détails de la note")
			else: 
				Entry(f, textvariable=self.residentValues[count], width=30).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveResidentBt=Button(s, image=self.imgSave, command=self.createResident)
		self.saveResidentBt.bind("<Return>", self.createResident)
		self.saveResidentBt.pack(side=LEFT)
		self.balloon.bind(self.saveResidentBt, u"Enregistrer")
		self.deleteResidentBt=Button(s, image=self.imgDelete, command=self.deleteResident, state=DISABLED)
		self.deleteResidentBt.bind("<Return>", self.deleteResident)
		self.deleteResidentBt.pack(side=LEFT)
		self.balloon.bind(self.deleteResidentBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des Resident Choisi").pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar=Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listResident=Listbox(s)
		self.listResident.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=8)
		self.listResident.bind("<ButtonRelease-1>",self.selectResident)
		scrollbar.config(command=self.listResident.yview)
		self.listResident.pack(side=TOP, fill=X)
		self.balloon.bind(self.listResident, u"Séléctionner un Resident Choisi\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.listObjectRE=[Place,Person]
		self.residentValues[0].set("ID:"+str(self.listObject[self.index].id)+" "+self.listObject[self.index].contact.lname)
		self.searchResident()

	def ctrlListPerson(self,field): # index 0
		PersonListGUI(balloon=self.balloon, field=field, index=1, listObject=self.listObjectRE, log=self.log, path=self.path)

	def ctrlNotes(self,field,title):
		n=NotesGUI(field=field,title=title, log=self.log, path=self.path)

	def residentOld(self, value):
		old = (("B", "Baby"),("K", "Kid"),("T", "Teen"),("A", "Adult"),("M", "Mature"),("O", "Old"),) 
		for n in old:
			if n[1] == value: self.residentValues[2].set(n[0])

	def residentPets(self, value):
		pets = (("NO", "Aucun"),("D1", "1 Chien"),("D2", "2 Chiens"),("D3", "3 Chiens"),("C1", "1 Chat"),("C2", "2 Chats"),("C3", "3 Chats"),("O", "Oiseau"),("R", "Rongeur"),("A", "Autre"),)
		for n in pets:
			if n[1] == value: self.residentValues[4].set(n[0])

	def verifyResident(self):
		if self.residentValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Résident est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createResident(self, event=None):
		if self.verifyResident():
			if  self.deleteResidentBt.config()["state"][4] == "normal":
				self.modifyResident()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouveau Résident ?\n" % self.residentValues[1].get()):
					Resident(stay=self.listObject[self.index],
						person=self.listObjectRE[1],
						old=self.residentValues[2].get().encode("utf-8"),
						passport=self.residentValues[3].get().encode("utf-8"),
						pets=self.residentValues[4].get().encode("utf-8"),
						notes=self.residentValues[5].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchResident()
				self.clearFieldResident()

	def modifyResident(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le Résident %s ?" % self.selectedResident.person.fname+" - "+self.selectedResident.person.lname):
			self.selectedResident.person=self.listObjectRE[1] 
			self.selectedResident.old=self.residentValues[2].get().encode("utf-8")
			self.selectedResident.passport=self.residentValues[3].get().encode("utf-8")
			self.selectedResident.pets=self.residentValues[4].get().encode("utf-8")
			self.selectedResident.notes=self.residentValues[5].get().encode("utf-8")
			self.searchResident()
		self.deleteResidentBt.config(state=DISABLED)
		self.clearFieldResident()

	def deleteResident(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer le Résident %s ?\nCette opération est irréversible !" % self.selectedResident.person.fname+" - "+self.selectedResident.person.lname):
			Resident.delete(self.selectedResident.id)
			self.searchResident()            
		self.deleteResidentBt.config(state=DISABLED)
		self.clearFieldResident()
	# FIN de la gestion du module Resident -------------------------------------------------------------------------------------------------------

class StayBillGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Pièces de vente liée au Séjour")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.balloon=balloon
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Reservation-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Reservation-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tStayBillGUI\tStart")
		self.makeStayBill()

	# DEBUT de la gestion du module StayBill // Vue depuis la gestion des Séjour----------------------------------------------------
	def clearFieldStayBill(self):
		# Mise a zéro des champs
		self.stayBillValues[1].set("")
		self.listObjectSB=[Place,Bill]
		# Affichage du nombre de Factures rattaché à ce séjour
		result = StayBill.select(StayBill.q.stay==self.listObject[self.index])
		count=0
		for row in result:
			count+=1
		if count < 2:
			self.field.set(str(count)+" Facture")
		else:
			self.field.set(str(count)+" Factures")

	def selectStayBill(self, event):
		if self.listStayBill.get(0)!="":
			result = StayBill.select(StayBill.q.id==self.idListStayBill[int(self.listStayBill.curselection()[0])])
			for row in result:
				self.selectedStayBill = row
			self.listObjectSB[1]=self.selectedStayBill.bill
			if self.selectedStayBill.bill != None:self.stayBillValues[1].set(self.selectedStayBill.bill)
			# activation du bouton supprimer
			self.deleteStayBillBt.config(state=NORMAL)

	def searchStayBill(self, event=None):
		self.listStayBill.delete(0,END)
		self.idListStayBill = []
		result = StayBill.select(StayBill.q.stay==self.listObject[self.index],orderBy=StayBill.q.id)
		for row in result:
			self.listStayBill.insert(END, str(row.id)+" - "+str(row.bill))
			self.idListStayBill.append(row.id)

	def makeStayBill(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Pièce").pack(side=TOP, fill=X)
		stayBillLabels = (u"Séjour", u"Pièce réf.")
		self.stayBillValues = [StringVar(),StringVar()]
		count = 0
		for name in stayBillLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Séjour
				Entry(f, textvariable=self.stayBillValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			else: # Bill
				Entry(f, textvariable=self.stayBillValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myBill=Button(f, image=self.imgSearch, command=lambda x=self.stayBillValues[count]:self.ctrlListBill(x), padx=4, pady=1)
				myBill.pack(side=RIGHT)
				self.balloon.bind(myBill, u"Séléctionner une Pièce")
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveStayBillBt=Button(s, image=self.imgSave, command=self.createStayBill)
		self.saveStayBillBt.bind("<Return>", self.createStayBill)
		self.saveStayBillBt.pack(side=LEFT)
		self.balloon.bind(self.saveStayBillBt, u"Enregistrer")
		self.deleteStayBillBt=Button(s, image=self.imgDelete, command=self.deleteStayBill, state=DISABLED)
		self.deleteStayBillBt.bind("<Return>", self.deleteStayBill)
		self.deleteStayBillBt.pack(side=LEFT)
		self.balloon.bind(self.deleteStayBillBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des Pièces de vente").pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listStayBill = Listbox(s)
		self.listStayBill.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=10)
		self.listStayBill.bind("<ButtonRelease-1>",self.selectStayBill)
		scrollbar.config(command=self.listStayBill.yview)
		self.listStayBill.pack(side=TOP, fill=X)
		self.balloon.bind(self.listStayBill, u"Séléctionner une Facture liée\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.listObjectSB=[Place,Bill]
		self.stayBillValues[0].set("ID:"+str(self.listObject[self.index].id)+" "+self.listObject[self.index].contact.lname)
		self.searchStayBill()

	def ctrlListBill(self,field):
		BillList2GUI(balloon=self.balloon, field=field, index=1, listObject=self.listObjectSB, log=self.log, path=self.path)

	def verifyStayBill(self):
		if self.stayBillValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champs Facture est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createStayBill(self, event=None):
		if self.verifyStayBill():
			if  self.deleteStayBillBt.config()["state"][4] == "normal":
				self.modifyStayBill()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme une nouvelle Facture liée à ce séjour ?\n" % self.stayBillValues[1].get()):
					StayBill(stay=self.listObject[self.index],
						bill=self.listObjectSB[1],
						createDate=datetime.datetime.now()
					)
					self.searchStayBill()
				self.clearFieldStayBill()

	def modifyStayBill(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le Choix de la Facture liée %s ?" % self.selectedStayBill.bill):
			self.selectedStayBill.bill=self.listObjectSB[1]   
			self.searchStayBill()
		self.deleteStayBillBt.config(state=DISABLED)
		self.clearFieldStayBill()

	def deleteStayBill(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer la Facture liée %s ?\nCette opération est irréversible !" % self.selectedStayBill.bill):
			StayBill.delete(self.selectedStayBill.id)
			self.searchStayBill()            
		self.deleteStayBillBt.config(state=DISABLED)
		self.clearFieldStayBill()
	# FIN de la gestion du module StayBill // Vue depuis la gestion des Séjours (Stay)  -----------------------------------------------

class BillStayGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Séjour(s) liée à la pièce de vente")
		self.balloon=balloon
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Bill-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Bill-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tBillStayGUI\tStart")
		self.makeBillStay()

	# DEBUT de la gestion du module BillStay // Vue depuis la gestion des Pièces de ventes (Bill)-----------------------------
	def clearFieldBillStay(self):
		# Mise a zéro des champs
		self.billStayValues[1].set("")
		self.listObjectSB=[Place,Stay]
		# Affichage du nombre de Séjour rattaché à cette facture
		result = StayBill.select(StayBill.q.bill==self.listObject[self.index])
		count=0
		for row in result:
			count+=1
		if count < 2:
			self.field.set(str(count)+" Séjour")
		else:
			self.field.set(str(count)+" Séjours")

	def selectBillStay(self, event):
		if self.listBillStay.get(0)!="":
			result = StayBill.select(StayBill.q.id==self.idListBillStay[int(self.listBillStay.curselection()[0])])
			for row in result:
				self.selectedBillStay = row
			self.listObjectSB[1]=self.selectedBillStay.stay
			if self.selectedBillStay.stay != None:self.billStayValues[1].set(self.selectedBillStay.stay)
			# activation du bouton supprimer
			self.deleteBillStayBt.config(state=NORMAL)

	def searchBillStay(self, event=None):
		self.listBillStay.delete(0,END)
		self.idListBillStay = []
		result = StayBill.select(StayBill.q.bill==self.listObject[self.index],orderBy=StayBill.q.id)
		for row in result:
			self.listBillStay.insert(END, str(row.id)+" - Réf: "+row.stay.voucher+" - "+str(row.stay))
			self.idListBillStay.append(row.id)

	def makeBillStay(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Séjour").pack(side=TOP, fill=X)
		billStayLabels = (u"Pièce réf.",u"Séjour")
		self.billStayValues = [StringVar(),StringVar()]
		count = 0
		for name in billStayLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Piece de vente ID
				Entry(f, textvariable=self.billStayValues[count], width=24, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
			else: # Séjour
				Entry(f, textvariable=self.billStayValues[count], width=21, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myStay=Button(f, image=self.imgSearch, command=lambda x=self.billStayValues[count]:self.ctrlListStay(x), padx=4, pady=1)
				myStay.pack(side=RIGHT)
				self.balloon.bind(myStay, u"Séléctionner un Séjour")
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveBillStayBt=Button(s, image=self.imgSave, command=self.createBillStay)
		self.saveBillStayBt.bind("<Return>", self.createBillStay)
		self.saveBillStayBt.pack(side=LEFT)
		self.balloon.bind(self.saveBillStayBt, u"Enregistrer")
		self.deleteBillStayBt=Button(s, image=self.imgDelete, command=self.deleteBillStay, state=DISABLED)
		self.deleteBillStayBt.bind("<Return>", self.deleteBillStay)
		self.deleteBillStayBt.pack(side=LEFT)
		self.balloon.bind(self.deleteBillStayBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		Label(leftFrame, text=u"Liste des séjours liés").pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listBillStay = Listbox(s)
		self.listBillStay.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=10)
		self.listBillStay.bind("<ButtonRelease-1>",self.selectBillStay)
		scrollbar.config(command=self.listBillStay.yview)
		self.listBillStay.pack(side=TOP, fill=X)
		self.balloon.bind(self.listBillStay, u"Séléctionner un séjour lié\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.billStayValues[0].set("ID:"+str(self.listObject[self.index].id)+" "+self.listObject[self.index].reference)
		self.listObjectSB=[Place,Stay]
		self.searchBillStay()

	def ctrlListStay(self,field):
		StayListGUI(balloon=self.balloon, field=field, index=1, listObject=self.listObjectSB, log=self.log, path=self.path)

	def verifyBillStay(self):
		if self.billStayValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le Séjour est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createBillStay(self, event=None):
		if self.verifyBillStay():
			if  self.deleteBillStayBt.config()["state"][4] == "normal":
				self.modifyBillStay()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme une nouveau séjour liée à cette facture ?\n" % self.billStayValues[1].get()):
					StayBill(bill=self.listObject[self.index],
						stay=self.listObjectSB[1],
						createDate=datetime.datetime.now()
					)
					self.searchBillStay()
				self.clearFieldBillStay()

	def modifyBillStay(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le séjour lié a cette facture %s ?" % self.selectedBillStay.stay):
			self.selectedBillStay.stay=self.listObjectSB[1]   
			self.searchBillStay()
		self.deleteBillStayBt.config(state=DISABLED)
		self.clearFieldBillStay()

	def deleteBillStay(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer le séjour lié %s ?\nCette opération est irréversible !" % self.selectedBillStay.stay):
			StayBill.delete(self.selectedBillStay.id)
			self.searchBillStay()            
		self.deleteBillStayBt.config(state=DISABLED)
		self.clearFieldBillStay()
	# FIN de la gestion du module BillStay // Vue depuis la gestion des Pièces de ventes (Bill)----------------------------------

class BillList2GUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des Pièces")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Bill-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Bill-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tBillList2GUI\tStart")
		self.makeListBill()

	def selectListBill(self, event):
		if self.listListBill.get(0)!="":
			result = Bill.select(Bill.q.id==self.idListListBill[int(self.listListBill.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row.reference+" - "+row.customer.lname)
				self.destroy()

	def searchListBill(self, event=None):
		if self.searchListBillValue.get() != "":
			self.listListBill.delete(0,END)
			self.idListListBill = []
			result = Bill.select(Bill.q.reference.startswith(self.searchListBillValue.get().encode("utf-8")), orderBy=Bill.q.date)
			for row in result:
				self.listListBill.insert(END, row.reference+" - "+row.customer.lname)
				self.idListListBill.append(row.id)
		else:
			self.listListBill.delete(0,END)
			self.idListListBill = []
			result = Bill.select(orderBy=Bill.q.date)
			for row in result:
				self.listListBill.insert(END, row.reference+" - "+row.customer.lname)
				self.idListListBill.append(row.id)

	def makeListBill(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste des Pièces").pack(side=TOP, fill=X)
		self.searchListBillValue = StringVar()
		s = Frame(leftFrame) 
		self.searchListBillEt = Entry(s,  width=43, textvariable=self.searchListBillValue, relief=GROOVE)
		self.searchListBillEt.bind("<KeyRelease>", self.searchListBill)
		self.searchListBillEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchListBillEt, u"Saisir les premiéres lettres d'une référence de pièce\npour une recherche plus précise,\nla liste est classée par Date.")
		#~ newBillBt=Button(s, image=self.imgNew, command=self.ctrlBill)
		#~ newBillBt.pack(side=RIGHT)
		#~ self.balloon.bind(newBillBt, u"Créer une nouvelle Pièce de vente")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListBill = Listbox(s)
		self.listListBill.config(yscrollcommand=scrollbar.set,width=43, selectmode=SINGLE, height=16)
		self.listListBill.bind("<ButtonRelease-1>",self.selectListBill)
		scrollbar.config(command=self.listListBill.yview)
		self.listListBill.pack(side=TOP, fill=X)
		self.balloon.bind(self.listListBill, u"Séléctionner une Pièces.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListBill()

	#~ def ctrlBill(self):
		#~ BillGUI(balloon=self.balloon, log=self.log, path=self.path)